﻿
using B.S.DataBase.MyProject.Domain.PatientMobileDevice;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Read.API.Appcation.Commands.TroubleCommand;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace MedicalPCTerminal.Read.API.Appcation.CommandHandlers.TroubleCommandHandlers
{
    /// <summary>
    /// 处理登陆命令
    /// </summary>
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<Me>>
    {
        private readonly SqlSugarContext sqlSugar;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="meRepository">仓储</param>
        public LoginCommandHandler(SqlSugarContext sqlSugar)
        {
            this.sqlSugar = sqlSugar;
        }
        public async Task<APIResult<Me>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<Me> result = new APIResult<Me>();
                var entity = sqlSugar.db.Queryable<Me>().Where(x => x.UserName == request.UserName && x.Password == request.Password).First();

                if (entity != null)
                {
                    result.Code = APIEnum.登录成功;
                    result.Msg = APIEnum.登录成功.ToString();
                    entity.Img = CreateTokenString();
                    result.data = entity;
                }
                else
                {
                    result.Code = APIEnum.登录失败密码或用户名错误;
                    result.Msg = APIEnum.登录失败密码或用户名错误.ToString();
                }
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
